﻿using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ObjectContextMigration
{
    /// <summary>
    /// Extracts entities internal components considering its structure and dependencies
    /// </summary>
    public class EntityComponentsExtractor
    {
        public List<EntityObject> GetAllDependentEntities(EntityObject entity) {
            List<EntityObject> result = new List<EntityObject>();
            Type entityCustomType = entity.GetType();
            PropertyInfo[] entityProperties = entityCustomType.GetProperties();
            foreach (PropertyInfo property in entityProperties)
            {
                Type type = property.PropertyType;
                if (type.BaseType == typeof(System.Data.Objects.DataClasses.RelatedEnd))
                {
                    foreach(EntityObject extractedEntity in this.ExtracChildEntitiesFromProperty(entity, property))
                        result.Add(extractedEntity);
                }
            }
            return result;
        }

        public List<EntityObject> ExtracChildEntitiesFromProperty(EntityObject parentEntity, PropertyInfo property)
        {
            List<EntityObject> result= new List<EntityObject>();
            Object propertyValue = property.GetValue(parentEntity, null);
            if(propertyValue.GetType().GetGenericTypeDefinition() == typeof(EntityCollection<>)) {
                IEnumerable<EntityObject> entities = (IEnumerable<EntityObject>)propertyValue;
                foreach (EntityObject entity in entities)
                {
                    result.Add(entity);
                }
            }
            return result;
        }
    }
}
